/*
 * Gedigarr - Falling block game.
 * Copyright (C) 2010  BoredCorp
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * r2 - 2010-04-28 - Refactor
 * Changed class mechanics completely. Now each instance is its own timer.
 * 
 * r1 - 2010-04-07 - Initial revision
 * Begun transfering timers out of GameState. Rotate complete, others to follow.
 * 
 */
package gedigarr.timers;

/**
 * Handles ticks and timer management.
 * 
 * 
 * @author JC
 */
public class GameTimer {
  private static int nextID = 0;
  private int timerID;
  private long initial;
  private long count;
  private long tickBase;
  private long tick;
  private boolean posTick;

  // a counter
  public GameTimer( long initial ) {
    this( initial, Long.MAX_VALUE );
  }

  // a timer
  public GameTimer( long initial, long tickBase ) {
    this.timerID = GameTimer.nextID++;
    this.initial = initial;
    this.tickBase = tickBase;
    this.posTick = tickBase >= 0 ? true : false;
    reset();
  }

  public void reset() {
    this.count = this.initial;
    this.tick = this.tickBase;
  }

  public long getTick() {
    return this.tick;
  }

  public void inc( long inc ) {
    this.count += inc;
  }

  public long getCount() {
    return this.count;
  }

  /**
   * Changes the tick rate of this timer.
   * @param tick The new tick rate. Note this does not change the base tick rate.
   *  ie the rate specified on construction.
   */
  public void setTick( long tick ) {
    this.tick = tick;
  }

  public boolean hasTicked() {
    if ( posTick ) {
      return this.count > this.tick;
    } else {
      return this.count < this.tick;
    }
  }

  public void tick() {
    if ( hasTicked() ) {
      if ( posTick ) {
        this.count -= this.tick;
      } else {
        this.count += this.tick;
      }
    }
  }

  @Override
  public String toString() {
    StringBuffer sb = new StringBuffer();
    sb.append( "id=" ).append( timerID );
    sb.append( ";count=" ).append( this.count );
    sb.append( ";tick=" ).append( this.tick );
    sb.append( ";hasTicked=" ).append( this.hasTicked() );
    return sb.toString();
  }
}
